﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using CIT.WMS.RM.Bll;

namespace CIT.WMS.RM
{
    public partial class FrmRMGroupS : Form
    {
        string billno = string.Empty;
        string row = string.Empty;
        string order = string.Empty;
        decimal FGQty = 0;
        bool isNew = true;
        int DetailNo = 0;
        string partnumber = string.Empty;
        //int DetailNoUpdate = 0;
        List<decimal> detailNoList = new List<decimal>();
         
        public FrmRMGroupS(string Billno,string Row, string Order)
        {
            InitializeComponent();
             billno = Billno;
             row = Row;
             order = Order;
        }
 

        private void FrmRMIn_Load(object sender, EventArgs e)
        {
            FormLoad();
        }

        public void FormLoad() 
        {
            DataTable Dt = Bll_RMIn.GetRMRowByCondition(billno, row, order);
            if (Dt != null && Dt.Rows.Count > 0)
            {
                labno.Text = billno + "-" + row + "-" + order;
                label1.Text = "良品数:" + Dt.Rows[0]["FGQty"].ToString() + Dt.Rows[0]["Unit"].ToString();
                FGQty = Convert.ToDecimal(Dt.Rows[0]["FGQty"]);
                 
            }
            else 
            {
                MessageBox.Show("该订单不存在");
                this.Close();
            }

            DataTable dtMaxDetailNo = Bll_RMIn.GetMaxDetailNo(billno, row, order);
            if (dtMaxDetailNo != null && dtMaxDetailNo.Rows.Count > 0 && (!string.IsNullOrEmpty(dtMaxDetailNo.Rows[0]["DetailNo"].ToString())))
            {
                //DetailNo = Convert.ToInt32(dtMaxDetailNo.Rows[0]["DetailNo"]);
                detailNoList.Clear();
                foreach (DataRow dr in dtMaxDetailNo.Rows) 
                {
                    detailNoList.Add(Convert.ToDecimal(dr["DetailNo"]));
                }
                DetailNo = detailNoList.Count; 
                //DetailNoUpdate = DetailNo+1;
                button2.Enabled = false;
            }
            else
            {
                DetailNo = 0;
                button1.Enabled = false;
                button2.Enabled = false;
            }
            button3.Enabled = false;
            partnumber = Dt.Rows[0]["PartNumber"].ToString().Trim();
            lab_msg.Text = "料号:" + Dt.Rows[0]["PartNumber"].ToString().Trim() + "\r\n当前托数:" + DetailNo.ToString() + "/" +    detailNoList.Count.ToString() + getMessageShow();

        }



        public void ReFormLoad()
        {
            DataTable Dt = Bll_RMIn.GetRMRowByCondition(billno, row, order);
            if (Dt != null && Dt.Rows.Count > 0)
            {
                labno.Text = billno + "-" + row + "-" + order;
                label1.Text = "良品数:" + Dt.Rows[0]["FGQty"].ToString() + Dt.Rows[0]["Unit"].ToString();
                FGQty = Convert.ToDecimal(Dt.Rows[0]["FGQty"]);

            }
            else
            {
                MessageBox.Show("该订单不存在");
                this.Close();
            }

            DataTable dtMaxDetailNo = Bll_RMIn.GetMaxDetailNo(billno, row, order);
            if (dtMaxDetailNo != null && dtMaxDetailNo.Rows.Count > 0 && (!string.IsNullOrEmpty(dtMaxDetailNo.Rows[0]["DetailNo"].ToString())))
            {
                //DetailNo = Convert.ToInt32(dtMaxDetailNo.Rows[0]["DetailNo"]);
                detailNoList.Clear();
                foreach (DataRow dr in dtMaxDetailNo.Rows)
                {
                    detailNoList.Add(Convert.ToDecimal(dr["DetailNo"]));
                }
                DetailNo = detailNoList.Count;
                //DetailNoUpdate = DetailNo+1;
                button2.Enabled = false;
            }
            else
            {
                DetailNo = 0;
                button1.Enabled = false;
                button2.Enabled = false;
            }
            button3.Enabled = false;

        }


        private void txtSN_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {

                if (!IsDataTime(this.txtDateCode.Text.ToString()))
                {
                    MessageBox.Show("输入格式有误，请输入8位时间格式，如：20180101");
                    return;
                }

                txtNum.Focus();

            }
        }

        private void txtNum_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                txtQty.Focus();
            }
        }

        private void txtQty_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                #region CHECK是否为空
                if (string.IsNullOrEmpty(txtDateCode.Text.ToString()))
                {
                    MessageBox.Show("生产日期不能为空!");
                    return;
                }
                if (string.IsNullOrEmpty(txtNum.Text.ToString()))
                {
                    MessageBox.Show("托数不能为空!");
                    return;
                }
                if (string.IsNullOrEmpty(txtQty.Text.ToString()))
                {
                    MessageBox.Show("数量不能为空!");
                    return;
                }
                #endregion

                if (!IsDataTime(this.txtDateCode.Text.ToString()))
                {
                    MessageBox.Show("输入格式有误，请输入8位时间格式，如：20180101");
                    return;
                }



                try
                {
                    Convert.ToInt32(txtNum.Text);
                    Convert.ToDecimal(txtQty.Text);
                }
                catch (Exception ex) 
                {
                    MessageBox.Show("请输入正确的数字格式！");
                    return;
                }


                if (Convert.ToInt32(txtNum.Text) <= 0) 
                {
                    MessageBox.Show("请输入正确的托数！");
                    return;
                }

                #region check分配数量

                decimal CheckQty = 0;
                decimal Count = Convert.ToDecimal(txtNum.Text);
                decimal tQty = Convert.ToDecimal(txtQty.Text);
                var DtDetails = Bll_RMIn.GetISRMD(billno, row, order);
                if (DtDetails != null && DtDetails.Rows.Count > 0)
                {
                    foreach (DataRow dr in DtDetails.Rows)
                    {
                        if (isNew)
                        {
                            CheckQty = CheckQty + Convert.ToDecimal(dr["PlanQty"]);
                        }
                        else
                        {
                            if (detailNoList[DetailNo] != Convert.ToInt32(dr["DetailNo"]))
                            {
                                CheckQty = CheckQty + Convert.ToDecimal(dr["PlanQty"]);
                            }
                        }
                         
                    }
                }
                //else
                //{
                //    MessageBox.Show("没有该订单行信息，数据错误!");
                //    return;
                //}
                string isOverStatus = "1";
                if (Count * tQty > (FGQty - CheckQty))
                {
                    MessageBox.Show("分配数量超过剩余可分配数量!");
                    return;
                }
                else if (Count * tQty == (FGQty - CheckQty)) 
                {
                    isOverStatus = "2";
                }


                #endregion
                var DtInStock = Bll_RMIn.GetInStockByCondition(" and BillNo='" + billno + "'");
                var DtInStockDetails = Bll_RMIn.GetRMRowsByCondition(billno, row, order);
                var drInfo = DtInStockDetails.Rows[0];

                if (isNew)
                {
                    #region 新增按托分配

                    var AreaStandard = "";
                    var listAreaStandard = GetPartNumberRMClod();

                    if (listAreaStandard.Contains(drInfo["PartNumber"].ToString().Trim()))
                    {
                        AreaStandard = "RM-COLD";
                    }
                    decimal beginDetail=0;
                    if(detailNoList.Count>0)
                    {
                        beginDetail=detailNoList[detailNoList.Count-1];
                    }
                     
                    //var result = Bll_RMIn.InsertNewDetail(billno, row, order,Convert.ToInt32(Count), txtDateCode.Text, AreaStandard, drInfo["RelatedBill"].ToString(), drInfo["PartNumber"].ToString(), drInfo["Version"].ToString(), txtQty.Text, drInfo["Unit"].ToString(), DtInStock.Rows[0]["Storage_SN"].ToString(), DetailNo);
                    var result = Bll_RMIn.InsertNewDetail(billno, row, order, Convert.ToInt32(Count), txtDateCode.Text, AreaStandard, drInfo["RelatedBill"].ToString(), drInfo["PartNumber"].ToString(), drInfo["Version"].ToString(), txtQty.Text, drInfo["Unit"].ToString(), DtInStock.Rows[0]["Storage_SN"].ToString(), beginDetail);
                    if (result)
                    {
                        DetailNo = DetailNo + Convert.ToInt32(Count);
                        //DetailNoUpdate = DetailNo;
                        txtDateCode.Text = "";
                        txtNum.Text = "";
                        txtQty.Text = "";
                        button1.Enabled = true;
                        txtDateCode.Focus();
                        updateRowStaus(isOverStatus);
                        ReFormLoad();
                        lab_msg.Text = "分配成功 \r\n料号:" + drInfo["PartNumber"].ToString().Trim() + "\r\n当前托数:" + DetailNo + "/" + detailNoList.Count + getMessageShow();
                    }
                    else
                    {
                        MessageBox.Show("分配失败!");
                        return;
                    }
                    #endregion
                }
                else
                {
                    //MessageBox.Show(billno + ":" + row + ":" + order + ":" + DetailNoUpdate.ToString() + ":" + txtDateCode.Text + ":" + txtQty.Text);
                    var result = Bll_RMIn.UpdateInStockDetail(billno, row, order, detailNoList[DetailNo].ToString(), txtDateCode.Text, txtQty.Text);
                    if (result)
                    {
                        updateRowStaus(isOverStatus);
                        lab_msg.Text = "修改成功 \r\n料号:" + drInfo["PartNumber"].ToString().Trim() + "\r\n当前托数:" + (DetailNo+1 )+ "/" + detailNoList.Count + getMessageShow();
                    }
                    else 
                    {
                        MessageBox.Show("修改失败!");
                        return;
                    }
                }
            }
        }


   

        public void updateRowStaus(string  isOverStatus) 
        {
            var result = Bll_RMIn.UpdateInStockRow(billno, row, order, isOverStatus);
        }

        public string getMessageShow() 
        {
            string meg = "\r\n";
            var DtInStockDetail= Bll_RMIn.GetISRMD(billno, row, order);
            decimal GroupD = 0;
            if (DtInStockDetail != null && DtInStockDetail.Rows.Count > 0) 
            {
                foreach (DataRow dr in DtInStockDetail.Rows) 
                {
                    GroupD += Convert.ToDecimal(dr["PlanQty"]);
                }
            }
            meg = meg +"处理数:"+ GroupD.ToString() + "/" + FGQty.ToString();
            return meg;
        }

        /// <summary>
        /// 判断时间格式
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private bool IsDataTime(string str)
        {
            System.IFormatProvider format = new System.Globalization.CultureInfo("zh-CN", true);
            try
            {
                DateTime.ParseExact(str, "yyyyMMdd", format);
                return true;
            }
            catch
            {
                return false;
            }
        }

        public List<string> GetPartNumberRMClod()
        {
            List<string> lists = new List<string>();
            lists.Add("GA-GL-71");
            lists.Add("SO-PA-22");
            lists.Add("ST8801TW");
            return lists;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //DetailNoUpdate = DetailNoUpdate - 1;
            DetailNo = DetailNo - 1;
            isNew = false;
            txtNum.Text = "1";
            txtNum.Enabled = false;
            if (DetailNo == 0) 
            {
                button1.Enabled = false;
  
            }
            if (detailNoList.Count > DetailNo) 
            {
                button2.Enabled = true;
            }
            var DtInStockDetail = Bll_RMIn.GetISRMDNum(billno, row, order, detailNoList[DetailNo].ToString());
            if (DtInStockDetail != null && DtInStockDetail.Rows.Count > 0) 
            {
                txtDateCode.Text = DtInStockDetail.Rows[0]["DateCode"].ToString();
                txtQty.Text = DtInStockDetail.Rows[0]["PlanQty"].ToString();
            }
            button3.Enabled = true;
            lab_msg.Text = "料号:" + partnumber + "\r\n当前托数:" + (DetailNo+1) + "/" + detailNoList.Count + getMessageShow();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //DetailNoUpdate = DetailNoUpdate +1;
            DetailNo = DetailNo + 1;
            button1.Enabled = true;
            if(detailNoList.Count<DetailNo+1)
            {
                isNew = true;
                button2.Enabled = false;
                txtNum.Text = "";
                txtNum.Enabled = true;
                txtDateCode.Text = "";
                txtDateCode.Focus();
                txtQty.Text = "";
                button3.Enabled = false;
            }
            else 
            {
                isNew = false;
                txtNum.Text = "1";
                txtNum.Enabled = false;
                var DtInStockDetail = Bll_RMIn.GetISRMDNum(billno, row, order, detailNoList[DetailNo].ToString());
                if (DtInStockDetail != null && DtInStockDetail.Rows.Count > 0)
                {
                    txtDateCode.Text = DtInStockDetail.Rows[0]["DateCode"].ToString();
                    txtQty.Text = DtInStockDetail.Rows[0]["PlanQty"].ToString();
                }
                button3.Enabled = true;
                lab_msg.Text = "料号:" + partnumber + "\r\n当前托数:" + (DetailNo + 1) + "/" + detailNoList.Count + getMessageShow();
            }

        }

        private void button3_Click(object sender, EventArgs e)
        {

            MessageBoxButtons messButton = MessageBoxButtons.OKCancel;

            DialogResult dr = MessageBox.Show("请是否确认删除该托信息！", "入库确认", messButton, MessageBoxIcon.None, MessageBoxDefaultButton.Button1);

            if (dr == DialogResult.Cancel)
            {
                return;
            }
            var DeleteBool = Bll_RMIn.DeleteRmRow(billno, row, order, detailNoList[DetailNo].ToString());
            if (DeleteBool)
            {
                Bll_RMIn.UpdateRmRow(billno, row, order);
                MessageBox.Show("删除成功!");
                detailNoList.Remove(detailNoList[DetailNo]);
                if (detailNoList.Count == 0)
                {
                    isNew = true;
                    txtNum.Text = "";
                    txtNum.Enabled = true;
                    txtDateCode.Text = "";
                    txtDateCode.Focus();
                    txtQty.Text = "";
                    button1.Enabled = false;
                    button2.Enabled = false;
                    button3.Enabled = false;
                    lab_msg.Text = "删除成功 \r\n料号:" + partnumber + "\r\n当前托数:0/" + detailNoList.Count + getMessageShow();
                }
                else
                {
                    if (DetailNo + 1 > detailNoList.Count)
                    {

                        isNew = true;
                        txtNum.Text = "";
                        txtNum.Enabled = true;
                        txtDateCode.Text = "";
                        txtDateCode.Focus();
                        txtQty.Text = "";
                        button1.Enabled = true;
                        button2.Enabled = false;
                        button3.Enabled = false;
                        lab_msg.Text = "删除成功 \r\n料号:" + partnumber + "\r\n当前托数:" + DetailNo + "/" + detailNoList.Count + getMessageShow();
                    }
                    else
                    {
                        isNew = false;
                        txtNum.Text = "1";
                        txtNum.Enabled = false;
                        var DtInStockDetail = Bll_RMIn.GetISRMDNum(billno, row, order, detailNoList[DetailNo].ToString());
                        if (DtInStockDetail != null && DtInStockDetail.Rows.Count > 0)
                        {
                            txtDateCode.Text = DtInStockDetail.Rows[0]["DateCode"].ToString();
                            txtQty.Text = DtInStockDetail.Rows[0]["PlanQty"].ToString();
                        }
                        button3.Enabled = true;
                        lab_msg.Text = "删除成功 \r\n料号:" + partnumber + "\r\n当前托数:" + (DetailNo + 1) + "/" + detailNoList.Count + getMessageShow();
                    }
                    
                }
            
            }
            else 
            {
                MessageBox.Show("删除失败!");
            }

        }

    }
}